package vip.xiaonuo.biz.modular.dict.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.models.auth.In;
import javafx.concurrent.Task;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.biz.modular.dict.entity.*;
import vip.xiaonuo.biz.modular.dict.entity.KyEntity.*;
import vip.xiaonuo.biz.modular.dict.entity.dto.HbTask;
import vip.xiaonuo.biz.modular.dict.entity.dto.KyCamera;
import vip.xiaonuo.biz.modular.dict.mapper.HbCameraMapper;
import vip.xiaonuo.biz.modular.dict.service.*;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.hikservice.HikDto;
import vip.xiaonuo.common.hikservice.HikVo;
import vip.xiaonuo.common.kyservice.Kyhttp;
import vip.xiaonuo.common.pojo.CommonResult;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 鲲云API
 */
@RestController
public class KyController {

    @Resource
    private Kyhttp kyhttp;



    @Resource
    private HbCameraMapper hbCameraMapper;

    @Resource
    private HbAlgService hbAlgService;

    @Value("${kyservice.address}")
    private String kyaddress;

    @Resource
    private CommonCacheOperator commonCacheOperator;

    @Resource
    private HbAlarmService hbAlarmService;

    @Autowired
    private KyService kyService;

    @Resource
    private IHikService iHikService;

    private static Map<Integer, String> algIdToAlgLevel;


    private static Map<String, String> indexCodeToAreaCode;


    private static Map<String, String> indexCodeToAreaName;

    private static Map<String, String> indexCodeToCameraName;

    /**
     * ky 回调接口 接收报警数据
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/ky/callback")
    public JSONObject getCameraList(@RequestBody JSONObject jsonObject) {
        Object algLevel = commonCacheOperator.get("algLevel");
        if (ObjectUtil.isEmpty(algIdToAlgLevel) || Integer.valueOf(String.valueOf(algLevel)) == 1) {
            commonCacheOperator.put("algLevel", 0);
            List<HbAlg> list = hbAlgService.list();
            algIdToAlgLevel = list.stream().collect(Collectors.toMap(HbAlg::getId, HbAlg::getAlgLevel));

            List<HbCamera> hbCameras = hbCameraMapper.selectList(null);
            indexCodeToAreaCode = hbCameras.stream().collect(Collectors.toMap(HbCamera::getIndexCode, HbCamera::getAreaCode));
            indexCodeToAreaName = hbCameras.stream().collect(Collectors.toMap(HbCamera::getIndexCode, HbCamera::getAreaName));
            indexCodeToCameraName = hbCameras.stream().collect(Collectors.toMap(HbCamera::getIndexCode, HbCamera::getName));
        }

        System.out.println(jsonObject);
        HbAlarm hbAlarm = new HbAlarm();
        String alarmUrl = jsonObject.getStr("alarmUrl");
        String url = alarmUrl.split(":8081")[1];
        alarmUrl = kyaddress + url;
        hbAlarm.setAlarmImg(alarmUrl);
        hbAlarm.setAlarmTime(new Date());
        hbAlarm.setAlarmType(jsonObject.getStr("algorithmName"));
        //获取摄像头名称
        String str = jsonObject.getStr("cameraDeviceName");
        hbAlarm.setAlarmLevel(algIdToAlgLevel.get(jsonObject.getInt("algorithmId")));
        //System.out.println(str);
        String indexCode = jsonObject.getStr("cameraDeviceName");
        hbAlarm.setIndexCode(indexCode);
        hbAlarm.setCameraName(indexCodeToCameraName.get(indexCode));
        hbAlarm.setAreaCode(indexCodeToAreaCode.get(indexCode));
        hbAlarm.setAreaName(indexCodeToAreaName.get(indexCode));
        hbAlarmService.save(hbAlarm);
        return null;
    }

    /**
     * 算法组  与摄像头算法关联  并开启视频检测任务
     *
     * @param kyCamera
     * @return
     */
    @PostMapping("/ky/start/task")
    public CommonResult starTtask(@RequestBody KyCamera kyCamera) {
        new Thread(()->{
            kyService.starTtask(kyCamera);
        }).start();

        return CommonResult.ok();

    }




   /* @GetMapping("/ky/getTaskList")
    public CommonResult<Page<HbTask>> getTaskList(@RequestParam(required = false) String taskName, Integer current, Integer size) {
        // 所有摄像头的 indexCode
        List<HbCamera> hbCameras = hbCameraMapper.selectList(null);
        Map<String,HbCamera> indexCodeToName = new HashMap<>();

        for (HbCamera hbCamera : hbCameras) {
            indexCodeToName.put(hbCamera.getIndexCode(),hbCamera);
        }

        //获取所有任务
        List<HbAlg> list = hbAlgService.list();
        Map<String, Integer> nameToIdMap = list.stream().collect(Collectors.toMap(HbAlg::getAlgName, HbAlg::getId));
        List<Integer> algIdLsit = new ArrayList<>();
        Map<String,List<String>> algToCameraId = new HashMap<>();
        //获取所有的任务
        JSONArray taskList = kyhttp.getTaskList();
        Set<String> indexCodeSet = new HashSet<>();
        for (Object o : taskList) {
            ATask aTask = JSONUtil.toBean(JSONUtil.parseObj(o), ATask.class);
            //获取任务详情
            JSONArray taskDetail = kyhttp.getTaskDetail(aTask.getId());
            //List<ATaskDetail> taskListEntity = new ArrayList<>();
            for (Object taskde : taskDetail) {
                ATaskDetail aTaskDetail = JSONUtil.toBean(JSONUtil.parseObj(taskde), ATaskDetail.class);
                String algName = aTaskDetail.getName();
                List<ATaskDetailConfig> configList = aTaskDetail.getConfigList();
                if(ObjectUtil.isNotEmpty(configList)){
                    List<String> cameraIndexCodeList = configList.stream().map(ATaskDetailConfig::getName).collect(Collectors.toList());
                    indexCodeSet.addAll(cameraIndexCodeList);
                    algToCameraId.put(algName ,cameraIndexCodeList);
                }
            }
        }

        List<HbTask> hbTasks = new ArrayList<>();

        for (String indexCode : indexCodeSet) {
            List<String> algList = new ArrayList<>();
            for (String s : algToCameraId.keySet()) {
                if(algToCameraId.get(s).contains(indexCode)){
                    algList.add(s);
                }
            }
            HbTask hbTask = new HbTask();
            hbTask.setIndexCode(indexCode);
            hbTask.setTaskName(indexCodeToName.get(indexCode).getName());
            JSONObject cameraList = kyhttp.getCameraList(indexCode);
            JSONArray jsonArray = cameraList.getJSONObject("data").getJSONArray("cameraList");
            //判断摄像头是否存在

            if(ObjectUtil.isNotEmpty(jsonArray)){
                String status = JSONUtil.parseObj(jsonArray.get(0)).getStr("status");
                hbTask.setStatus(status);
                hbTask.setAlgorithm(algList.toString().replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", ""));
                hbTask.setCaraemName(indexCodeToName.get(indexCode).getAreaName() + "  ##  "  + indexCodeToName.get(indexCode).getName());
                if(ObjectUtil.isNotEmpty(taskName)){
                    if(indexCodeToName.get(indexCode).getName().contains(taskName.trim())){
                        hbTasks.add(hbTask);
                    }
                }else{
                    hbTasks.add(hbTask);
                }
            }
        }

        //Page
        List<HbTask> collect = hbTasks.stream()
                .skip(size * (current - 1))
                .limit(size)
                .collect(Collectors.toList());
        Page<HbTask> page = new Page<>();

        for (int i = 0; i < collect.size(); i++) {
            collect.get(i).setId(i + 1);
        }


        if (collect.size() < size) {
            page.setPages(1);
        } else {
            page.setPages((collect.size() / size) + 1);
        }


        page.setSize(size);
        page.setTotal(hbTasks.size());
        page.setCurrent(current);
        page.setRecords(collect);
        return CommonResult.data(page);
    }*/

    /**
     * 开启任务
     *
     * @return
     */
    @GetMapping("/ky/startTask")
    public CommonResult startTask(@RequestParam Integer taskId) {
        new Thread(()->{
            JSONObject entries = kyhttp.startTask(taskId);
        }).start();
        return CommonResult.ok();
    }
    @GetMapping("/ky/stopTask")
    public CommonResult stopTask(@RequestParam Integer taskId) {
        kyhttp.stopTask(taskId);
        return CommonResult.ok("任务停止成功");


    }


    /**
     * 获取单个摄像头与算法的关联关系
     * @param indexCode  摄像头标识 indexCode
     * @return
     */
    @GetMapping("/ky/getAboutCarameAlg")
    public CommonResult getAboutCarameAlg(@RequestParam String indexCode) {
        List<Integer> data = kyService.getAboutCarameAlg(indexCode);
        return CommonResult.data(data);
    }


    /**
     * indexCode 编码
     * @param indexCode
     * @return
     */
    @GetMapping("/ky/del")
    public CommonResult kydel(@RequestParam String indexCode) {

        //获取算法ID的与名称的对应关系
        JSONObject alg = kyhttp.getAlg();
        JSONArray jsonArray = alg.getJSONObject("data").getJSONArray("algoConfig");
        Map<String,Integer> nameToAlgId = new HashMap<>();
        for (Object o : jsonArray) {
            JSONObject algOne = JSONUtil.parseObj(o);
            nameToAlgId.put(algOne.getStr("name"),algOne.getInt("task_key"));
        }
        //获取摄像头id 与 名称的对应关系


        JSONArray cameraByKey = kyhttp.getCameraByKey(indexCode);
        ACamera aCamera = JSONUtil.toBean(JSONUtil.parseObj(cameraByKey.get(0)), ACamera.class);

        //获取所有的任务
        JSONArray taskList = kyhttp.getTaskList();
        Set<String> indexCodeSet = new HashSet<>();
        for (Object o : taskList) {
            ATask aTask = JSONUtil.toBean(JSONUtil.parseObj(o), ATask.class);
            //获取任务详情
            JSONArray taskDetail = kyhttp.getTaskDetail(aTask.getId());
            for (Object taskde : taskDetail) {
                System.out.println(taskde);
                ATaskDetail aTaskDetail = JSONUtil.toBean(JSONUtil.parseObj(taskde), ATaskDetail.class);
                List<ATaskDetailConfig> configList = aTaskDetail.getConfigList();
                List<String> cameraIdList = new ArrayList<>();
                if(ObjectUtil.isNotEmpty(configList)){
                    for (ATaskDetailConfig aTaskDetailConfig : configList) {
                        cameraIdList.add(String.valueOf(aTaskDetailConfig.getCameraId()));
                    }
                    cameraIdList.remove(String.valueOf(aCamera.getId()));
                    kyhttp.taskAlgAndCamare(aTask.getId(),String.valueOf(nameToAlgId.get(aTaskDetail.getName())),cameraIdList);
                }
            }
            System.out.println(kyhttp.stopTask(aTask.getId()));
            System.out.println(kyhttp.startTask(aTask.getId()));
        }

        return CommonResult.ok();
    }

    /**
     * 剩余算力
     * @return
     */
    @GetMapping("/ky/residue/alg")
    public CommonResult residueAlg() {
        return CommonResult.data(kyService.residueAlg());
    }




    @GetMapping("/ky/getTaskList")
    public CommonResult<Page<AKyTask>>  getTaskListBykey(@RequestParam(required = false) String taskName, Integer current, Integer size) {
        return CommonResult.data(kyService.getTaskList(taskName,current,size));
    }


    @PostMapping("/ky/task/add")
    public CommonResult  add(@RequestBody KyCreateTask kyCreateTask) {
        boolean task = kyService.createTask(kyCreateTask);
        if(kyCreateTask.getType().equals("1")){
            return CommonResult.ok("任务创建并启用成功");
        }else{
            return CommonResult.ok("任务创建并禁用成功");
        }
    }

    @PostMapping("/ky/task/edit")
    public CommonResult  edit(@RequestBody KyCreateTask kyCreateTask) {
        boolean task = kyService.editTask(kyCreateTask);
        return CommonResult.ok("任务创建并禁用成功");
    }


    @GetMapping("/ky/task/del")
    public CommonResult taskDel(@RequestParam Integer id) {
        boolean task = kyService.taskDel(id);
        return CommonResult.ok("任务删除成功");
    }


    /**
     * 快速配置：：： 算法组与单个算法配置相关  接口重构
     * @param kyCamera
     * @return
     */
    @GetMapping("/ky/start/task1")
    public CommonResult task(@RequestBody KyCamera kyCamera) {
        return kyService.task(kyCamera);
    }
}
